<?php
namespace app\index\controller;

use think\Controller;
use think\Request;
use think\Session;
use think\Cookie;

//防伪查询
class Fw extends Controller{
	
	//追溯码结果
    public function index(){
		//https://securitycode.weiyianws.com/#/trace-result?a=24065&c=12564001862764842607&b=45556
		
		$request = Request::instance();
		
		if(isset($_GET['zscode'])){
			//?zscode=123456
			$zscode = trim($_GET['zscode']);
		}else{
			//从?123456
			$url = $request->url();
			$arr = explode('?',$url);
			$zscode = end($arr);
		}
		
		if(!preg_match('/^\d{6,60}$/',$zscode)){
			return view('index_error',['zscode'=>'格式错误','msg'=>'追溯码错误']);
		}
		
		$pm = [
			'zssCode' => $zscode
		];
		$res = \ServerHelper::post('^/fw/index',$pm);
		$data = $this->J($res);
		
		if(empty($data['flag'])){
			return view('index_error',['zscode'=>$zscode,'msg'=>$data['msg']]);
		}
		if(empty($data['data']['productinfo']['name'])){
			return view('index_error',['zscode'=>$zscode,'msg'=>'该追溯码未关联商品，请关联后再查询！']);
		}
		return view('',$data);
    }
	
	//查询防伪码
	public function query(){
		
		$req = Request::instance();
		$zscode = $req->param('zscode');
		if($req->isPost()){
			if(!preg_match('/^\d+$/',$zscode)){
				ajax('参数错误');
			}
			$fwcode = $req->param('fwcode');
			if(!preg_match('/^\d+$/',$fwcode)){
				ajax('防伪码输入不正确');
			}
			$pm = [
				'zssCode' => $zscode,
				'fwcode' => $fwcode,
			];
			$response = \ServerHelper::post('^/fw/fwquery',$pm);
			$data = $this->J($response);
			if(empty($data['flag'])){
				ajax($data['msg']);
			}
			
			ajax('SUCCESS',true,$data['data']);
		}
		
		if(!preg_match('/^\d+$/',$zscode)){
			$this->error('参数错误');
		}
		return view('',['zscode'=>$zscode]);
		
	}
	
	
	private function J($list){
		$data = json_decode($list,true);
		if(!isset($data['flag'])){
			__log($list,'welogin');
			if(Request::instance()->isAjax()){
				ajax('网络错误');
			}
			exit('net error');
		}
		return $data;
	}
	
}
